<template>
  <div class="inbound-record">
    <div class="page-header">
      <h2>入库记录</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索条件区域 -->
    <el-card class="search-card">
      <template #header>
        <span>搜索条件</span>
        <el-button type="text" @click="resetSearch" style="float: right;">重置</el-button>
      </template>
      
      <el-form :model="searchForm" inline class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户代码">
              <el-select v-model="searchForm.customerCode" filterable
                         placeholder="选择客户代码" clearable style="width: 100%;">
                <el-option v-for="customer in customers" :key="customer.customerCode"
                          :label="customer.customerCode" :value="customer.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-input v-model="searchForm.customerName" placeholder="客户名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品名称">
              <el-input v-model="searchForm.productName" placeholder="产品名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编码">
              <el-input v-model="searchForm.materialCode" placeholder="物料编码" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="厂内编号">
              <el-input v-model="searchForm.factoryNo" placeholder="厂内编号" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
                            <el-select v-model="searchForm.salesperson" filterable allow-create default-first-option
                         placeholder="选择或输入业务员" clearable style="width: 100%;">
                <el-option v-for="emp in employees" :key="emp.employeeCode"
                           :label="emp.employeeName" :value="emp.employeeName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入库日期">
              <el-date-picker 
                v-model="searchForm.dateRange" 
                type="daterange" 
                range-separator="至" 
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 入库记录列表 -->
    <el-card class="table-card">
      <template #header>
        <span>入库记录列表</span>
        <div style="float: right;">
          <el-tag type="success" size="small">
            共 {{ pagination.total }} 条记录
          </el-tag>
        </div>
      </template>

      <el-table 
        :data="recordList" 
        border 
        v-loading="loading"
        height="500"
        style="width: 100%">
        
        <el-table-column type="index" label="序号" width="60" fixed="left"/>
        
        <el-table-column prop="inboundNo" label="入库单号" width="140" fixed="left"/>
        <el-table-column prop="factoryNo" label="厂内编号" width="100" fixed="left"/>
        <el-table-column prop="customerCode" label="客户代码" width="100" fixed="left"/>
        <el-table-column prop="customerName" label="客户名称" width="120" fixed="left"/>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewDetail(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="deleteRecord(row)" :disabled="row.status !== '已入库'">
              删除
            </el-button>
          </template>
        </el-table-column>
        
        <el-table-column prop="productName" label="产品名称" width="150" show-overflow-tooltip/>
        <el-table-column prop="materialCode" label="物料编码" width="120" show-overflow-tooltip/>
        <el-table-column prop="layers" label="层数" width="80"/>
        <el-table-column prop="thickness" label="板厚" width="80"/>
        <el-table-column prop="surfaceTreatment" label="表面处理" width="100"/>
        <el-table-column prop="solderMask" label="阻焊" width="80"/>
        <el-table-column prop="character" label="字符" width="80"/>
        <el-table-column prop="deliverySize" label="交货尺寸" width="120"/>
        <el-table-column prop="orderQuantity" label="订单数量" width="100"/>
        <el-table-column prop="inboundQuantity" label="入库数量" width="100">
          <template #default="{ row }">
            <span style="color: #67C23A; font-weight: bold;">{{ row.inboundQuantity }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spareQuantity" label="备品数量" width="100"/>
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="{ row }">
            <span v-if="row.unitPrice">{{ row.unitPrice.toFixed(4) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="合计金额" width="120">
          <template #default="{ row }">
            <span v-if="row.totalAmount" style="color: #E6A23C; font-weight: bold;">
              ¥{{ row.totalAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="inboundDate" label="入库日期" width="120"/>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesperson" label="业务员" width="100"/>
        <el-table-column prop="project" label="项目" width="120" show-overflow-tooltip/>
        <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip/>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="入库记录详情" 
      width="800px">
      
      <el-descriptions :column="2" border v-if="currentRecord">
        <el-descriptions-item label="入库单号">{{ currentRecord.inboundNo }}</el-descriptions-item>
        <el-descriptions-item label="厂内编号">{{ currentRecord.factoryNo }}</el-descriptions-item>
        <el-descriptions-item label="客户代码">{{ currentRecord.customerCode }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentRecord.customerName }}</el-descriptions-item>
        <el-descriptions-item label="客户编号">{{ currentRecord.customerNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ currentRecord.productName }}</el-descriptions-item>
        <el-descriptions-item label="物料编码">{{ currentRecord.materialCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目">{{ currentRecord.project || '-' }}</el-descriptions-item>
        <el-descriptions-item label="毛坯">{{ currentRecord.roughMaterial || '-' }}</el-descriptions-item>
        <el-descriptions-item label="业务员">{{ currentRecord.salesperson || '-' }}</el-descriptions-item>
        
        <el-descriptions-item label="PCB技术参数" :span="2">
          <el-row :gutter="20">
            <el-col :span="6">层数: {{ currentRecord.layers || '-' }}</el-col>
            <el-col :span="6">板厚: {{ currentRecord.thickness || '-' }}</el-col>
            <el-col :span="6">表面处理: {{ currentRecord.surfaceTreatment || '-' }}</el-col>
            <el-col :span="6">阻焊: {{ currentRecord.solderMask || '-' }}</el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 10px;">
            <el-col :span="6">字符: {{ currentRecord.character || '-' }}</el-col>
            <el-col :span="6">板材: {{ currentRecord.boardMaterial || '-' }}</el-col>
            <el-col :span="6">交货尺寸: {{ currentRecord.deliverySize || '-' }}</el-col>
            <el-col :span="6">拼版: {{ currentRecord.panelization || '-' }}</el-col>
          </el-row>
        </el-descriptions-item>
        
        <el-descriptions-item label="订单数量">{{ currentRecord.orderQuantity }} PCS</el-descriptions-item>
        <el-descriptions-item label="入库数量">
          <span style="color: #67C23A; font-weight: bold;">{{ currentRecord.inboundQuantity }} PCS</span>
        </el-descriptions-item>
        <el-descriptions-item label="备品数量">{{ currentRecord.spareQuantity || 0 }} PCS</el-descriptions-item>
        <el-descriptions-item label="单价">
          <span v-if="currentRecord.unitPrice">¥{{ currentRecord.unitPrice.toFixed(4) }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="合计金额">
          <span v-if="currentRecord.totalAmount" style="color: #E6A23C; font-weight: bold;">
            ¥{{ currentRecord.totalAmount.toFixed(2) }}
          </span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="入库日期">{{ currentRecord.inboundDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentRecord.status)" size="small">
            {{ currentRecord.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentRecord.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentRecord.remark || '-' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getInboundRecords, 
  deleteInbound, 
  getCustomerOptions, 
  getEmployeeOptions 
} from '@/api/warehouse'
import { Search, Refresh, RefreshLeft } from '@element-plus/icons-vue'

export default {
  name: 'InboundRecord',
  components: {
    Search,
    Refresh,
    RefreshLeft
  },
  setup() {
    const loading = ref(false)
    const detailDialogVisible = ref(false)
    const currentRecord = ref(null)

    // 搜索表单
    const searchForm = reactive({
      customerCode: '',
      customerName: '',
      productName: '',
      materialCode: '',
      factoryNo: '',
      salesperson: '',
      dateRange: []
    })

    // 分页信息
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 记录列表
    const recordList = ref([])
    
    // 基础数据
    const customers = ref([])
    const employees = ref([])

    // 计算属性：搜索参数
    const searchParams = computed(() => {
      const params = {
        current: pagination.current,
        size: pagination.size,
        ...searchForm
      }
      
      // 处理日期范围
      if (searchForm.dateRange && searchForm.dateRange.length === 2) {
        params.startDate = searchForm.dateRange[0]
        params.endDate = searchForm.dateRange[1]
      }
      delete params.dateRange
      
      // 移除空值
      Object.keys(params).forEach(key => {
        if (params[key] === '' || params[key] === null || params[key] === undefined) {
          delete params[key]
        }
      })
      
      return params
    })

    // 获取入库记录列表
    const fetchRecordList = async () => {
      try {
        loading.value = true
        const response = await getInboundRecords(searchParams.value)
        
        if (response.code === 200) {
          recordList.value = response.data.records || []
          pagination.total = response.data.total || 0
        }
      } catch (error) {
        console.error('获取入库记录失败:', error)
        ElMessage.error('获取入库记录失败')
      } finally {
        loading.value = false
      }
    }

    // 获取基础数据
    const fetchBaseData = async () => {
      try {
        const [customerRes, employeeRes] = await Promise.all([
          getCustomerOptions(),
          getEmployeeOptions()
        ])
        
        if (customerRes.code === 200) {
          customers.value = customerRes.data || []
        }
        
        if (employeeRes.code === 200) {
          employees.value = employeeRes.data || []
        }
      } catch (error) {
        console.error('获取基础数据失败:', error)
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchRecordList()
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        customerCode: '',
        customerName: '',
        productName: '',
        materialCode: '',
        factoryNo: '',
        salesperson: '',
        dateRange: []
      })
      pagination.current = 1
      fetchRecordList()
    }

    // 刷新数据
    const refreshData = () => {
      fetchRecordList()
    }

    // 分页变化
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      fetchRecordList()
    }

    const handleCurrentChange = (val) => {
      pagination.current = val
      fetchRecordList()
    }

    // 查看详情
    const viewDetail = (row) => {
      currentRecord.value = row
      detailDialogVisible.value = true
    }

    // 删除记录
    const deleteRecord = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确认删除入库单号为"${row.inboundNo}"的记录吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await deleteInbound(row.id)
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          fetchRecordList() // 刷新列表
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case '已入库':
          return 'success'
        case '已取消':
          return 'danger'
        default:
          return 'info'
      }
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    // 初始化
    onMounted(() => {
      fetchBaseData()
      fetchRecordList()
    })

    return {
      loading,
      detailDialogVisible,
      currentRecord,
      searchForm,
      pagination,
      recordList,
      customers,
      employees,
      handleSearch,
      resetSearch,
      refreshData,
      handleSizeChange,
      handleCurrentChange,
      viewDetail,
      deleteRecord,
      getStatusType,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.inbound-record {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-table {
  font-size: 14px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}

:deep(.el-descriptions-item__label) {
  font-weight: bold;
  background-color: #fafafa;
}
</style> 